#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_io.h"
#include "hi_time.h"
#include "humidity.h"
#include "hcsr04.h"

// 超声波传感器和土壤湿度传感器的控制引脚
#define ULTRASONIC_CONTROL_GPIO 10
#define SOIL_CONTROL_GPIO 11

// 初始化超声波传感器
void Ultrasonic_Init(void) {
    IoTGpioInit(TRIG_GPIO);
    IoTGpioInit(ECHO_GPIO);

    hi_io_set_func(ECHO_GPIO, HI_IO_FUNC_GPIO_9_GPIO);
    IoTGpioSetDir(ECHO_GPIO, IOT_GPIO_DIR_IN);

    hi_io_set_func(TRIG_GPIO, HI_IO_FUNC_GPIO_12_GPIO);
    IoTGpioSetDir(TRIG_GPIO, IOT_GPIO_DIR_OUT);
}

// 获取距离的函数
float guide_Getdistance(void)
{
    static unsigned long start_time = 0, time = 0;
    float distance = 0.0;
    unsigned int flag = 0;
    IotGpioValue value = IOT_GPIO_VALUE0;

    IoTGpioSetOutputVal(TRIG_GPIO, IOT_GPIO_VALUE1);
    hi_udelay(20);
    IoTGpioSetOutputVal(TRIG_GPIO, IOT_GPIO_VALUE0);

    while (1)
    {
        IoTGpioGetInputVal(ECHO_GPIO, &value);
        if (value == IOT_GPIO_VALUE1 && flag == 0)
        {
            start_time = hi_get_us();
            printf("\r\n ======= start_time:%d ======= \r\n", start_time);
            flag = 1;
        }
        if (value == IOT_GPIO_VALUE0 && flag == 1)
        {
            time = hi_get_us() - start_time;
            start_time = 0;
            printf("\r\n ======= time:%d ======= \r\n", time);
            break;
        }
    }

    distance = time * 0.034 / 2;
    return distance;
}

// 超声波传感器任务函数
static void UltrasonicTask(void *arg)
{
    (void) arg;
    printf("\r\n ===== start ultrasonic sensor test =====\r\r");

    // 初始化超声波传感器和控制引脚
    Ultrasonic_Init();
    IoTGpioInit(ULTRASONIC_CONTROL_GPIO);
    hi_io_set_func(ULTRASONIC_CONTROL_GPIO, HI_IO_FUNC_GPIO_10_GPIO);
    IoTGpioSetDir(ULTRASONIC_CONTROL_GPIO, IOT_GPIO_DIR_OUT);

    while (1)
    {
      
        float distance = Getdistance();
        printf("\r\n ===== distance is %f cm =====\r\n", distance);

        if (distance < 50)
        {
            IoTGpioSetOutputVal(ULTRASONIC_CONTROL_GPIO, IOT_GPIO_VALUE1);
            printf("\r\n ===== GPIO11 set to HIGH =====\r\n");
        }
        else
        {
            IoTGpioSetOutputVal(ULTRASONIC_CONTROL_GPIO, IOT_GPIO_VALUE0);
            printf("\r\n ===== GPIO11 set to LOW =====\r\n");
        }

        osDelay(200);
    }
}

// 导盲拐杖的任务配置
static void GuideSystemEntry(void)
{
    osThreadAttr_t attr = {0};

    // 配置超声波传感器任务
    attr.name = "UltrasonicTask";
    attr.stack_size = 4096;
    attr.priority = osPriorityNormal;

    if (osThreadNew((osThreadFunc_t)UltrasonicTask, NULL, &attr) == NULL) {
        printf("[GuideSystemEntry] create UltrasonicTask failed! \n");
    }

    // 配置土壤湿度传感器任务
    SoilHumiCtrl_Config();
}

// 系统启动时运行导盲拐杖任务
SYS_RUN(GuideSystemEntry);
